import React from 'react'
// ===================================================================== Temp
import Table from '#cpt/temp/Table'
import TableControls from '#cpt/temp/TableControls'
import SearchForm from '#cpt/temp/SearchForm'
// ===================================================================== global declare
const { $Lazy, $fn, $http } = window
// ===================================================================== Lazy
const Input				= $Lazy.load(()=>import('@antd/form/input'))
const DatePicker		= $Lazy.load(()=>import('@antd/form/datePicker'))
const RemarkModal 		= $Lazy.state(()=>import('./remark-modal'))
const ActionModal 		= $Lazy.state(()=>import('./action-modal'))
const InfoModal			= $Lazy.state(()=>import('./info-modal'))
const TipsModal			= $Lazy.state(()=>import('./tips-modal'))
const $time 			= $Lazy.file(()=>import('@com/utils/time'))
const confirm 			= $Lazy.file(()=>import('@antd/confirm'))
// ===================================================================== component
class Index extends React.Component{
	state = {
		data: [],
		forms : [
			{ label: '日期',		names: ['start','end'], 	name:'jz-time', type:'date-range' },
		],
	}

	model = {}

	key = 0
	
	cols = []
	
	componentDidMount(){
		this.init()
	}

	init = () => {
		const { uuid } = this.props?.data
		this.uuid = uuid
		this.model = {}
		if (uuid) {
			this.fetch().then(() => {
				this.searchFormRef.setValue({'jz-time': ''})
				this.setCols()
			})
		}
	}
	
	fetch = () => $fn.fetch.call(this,'qc-data/index', { param: {test_id: this.uuid}, isIndex: 1, callback: ({items}) => {
		const { pag: {current, totalPage}, data} = this.state
		const { levels } = this.props?.data
		const rows = {}
		this.key++
		if (current === totalPage || !items.length) {
			levels.forEach(v => {
				rows[`level${v}_value`] = ''
			})
			rows['index'] = items.length ? data.at(-1)['index'] + 1 : 0
			$time.then(f=>{
				const now = f.getNow()
				rows['entered_at'] = now
				this.setState({data: [...data, rows]}, () => {
					setTimeout(() => document.querySelector(`.ipt_${rows.index}-0 input`)?.focus(), 200)
				})
			})
		}
		this.props.chartRef.model = {...this.model}
		this.props.chartRef.init()
	}})
	
	setCols = () => {
		const { levels, result_type } = this.props?.data
		this.cols = [
			{ title: '',	children: [
				{ title: '',  			dataIndex: 'index', 		width: 40,	render: text => {
					const {current, pageSize} = this.state?.pag
					return pageSize * (current - 1) + text + 1
				}},
				{ title: '日期和时刻',	dataIndex: 'entered_at', 	width: 180, render: (text, rows) => <DatePicker key={this.key} tabIndex='-1' value={text} after={Date.now() + 86400000} onChanged={({value}) => rows.entered_at = value} /> }
			] }
		]
		levels.forEach((v, i) => {
			this.cols.push(
				{ title: `水平${v}`,	children: [
					{ title: '值',		dataIndex: `level${v}_value`,  		width: 100, render: (text, rows) => <Input key={this.key} p='请输入' className={`ipt_${rows.index}-${i}`} value={rows[`level${v}_value`]} onEnter={value => {
						const {current, pageSize, total} = this.state?.pag
						const index = pageSize * (current - 1) + rows['index'] + 1
						const param = { test_id: this.uuid, entered_at: rows.entered_at }
						const nextIpt = () => {
							if (levels.length > i + 1) {
								document.querySelector(`.ipt_${rows.index}-${i + 1} input`)?.focus()
							} else {
								document.querySelector(`.ipt_${rows.index + 1}-0 input`)?.focus()
							}
						}
						const formatParam = type => {
							if (type) {
								param['uuid'] = rows.uuid
							}
							levels.forEach(v => {
								param[`level${v}_value`] = rows[`level${v}_value`]
							})
						}
						if (result_type === '2' && levels.length === i + 1) {
							for (let i = 0; i < levels.length; i++) {
								if (!['N', 'P'].includes(rows[`level${v}_value`])) {
									$fn.msg.warning(`水平${v}的值错误，请输入 N/P`)
									return
								}
							}
						}
						if (levels.length > i + 1) {
							nextIpt()
							return
						}
						if (levels.length === i + 1 && index <= total) {
							formatParam(1)
							$http.submit(null, 'qc-data/edit', {param}).then(({violation}) => {
								if (violation?.length) this.tipsModalRef.refs.ref.open(violation)
								$fn.msg.success('更新成功！')
								nextIpt()
								this.fetch()
							})
							return
						}
						if (levels.length === i + 1 && index >= total) {
							formatParam(0)
							$http.submit(null, 'qc-data/add', {param}).then(({violation}) => {
								if (violation?.length) this.tipsModalRef.refs.ref.open(violation)
								$fn.msg.success('添加成功！')
								this.fetch()
							})
							return
						}
					}} onChanged={({value}) => {
						if (result_type === '2' && !['N', 'P'].includes(value)) {
							$fn.msg.warning('定性只能输入 N/P')
							return
						}
						rows[`level${v}_value`] = value
					}} /> },
					// { title: '是/否',	dataIndex: `level${v}_violation`, 	width: 60, render: (text, rows) => text ? '是' : '否' },
					{ title: '规则',		dataIndex: `level${v}_violation`, 	width: 100, render: (text) => <span style={{color: 'red'}}>{text}</span> },
				] }
			)
			if (result_type === '1') {
				this.cols[i + 1].children.push({ title: 'Z',		dataIndex: `level${v}_z`, 			width: 80 },
					{ title: '靶值',		dataIndex: `level${v}_avg`, 		width: 80 },
					{ title: '变异系数',	dataIndex: `level${v}_cv`, 			width: 80 }
				)
			}
		})
		
		this.cols.push(TableControls.controls.call(this, { width: 250 }))
		this.table.table.updateCol(this.cols)
	}
	
	// 表格操作按钮
	table_controls = (text, rows) => {
		const { levels, result_type } = this.props?.data
		const {current, pageSize, total} = this.state?.pag
		const index = pageSize * (current - 1) + rows['index'] + 1
		
		return [
			TableControls.click.call(this, index <= total ? '保存' : '添加', () => {
				const param = { test_id: this.uuid, entered_at: rows.entered_at }
				
				if (index <= total) {
					for (let i = 0; i < levels.length; i++) {
						if (result_type === '2' && !['N', 'P'].includes(rows[`level${levels[i]}_value`])) {
							$fn.msg.warning(`水平${levels[i]}的值错误，请输入 N/P`)
							return
						}
						param[`level${levels[i]}_value`] = rows[`level${levels[i]}_value`]
					}
					$http.submit(null, 'qc-data/edit', {param: { ...param, uuid: rows.uuid }}).then(({violation}) => {
						$fn.msg.success('更新成功！')
						if (violation?.length) this.tipsModalRef.refs.ref.open(violation)
						this.fetch()
					})
				} else {
					for (let i = 0; i < levels.length; i++) {
						if (result_type === '2' && !['N', 'P'].includes(rows[`level${levels[i]}_value`])) {
							$fn.msg.warning(`水平${levels[i]}的值错误，请输入 N/P`)
							return
						}
						param[`level${levels[i]}_value`] = rows[`level${levels[i]}_value`]
					}
					$http.submit(null, 'qc-data/add', {param}).then(({violation}) => {
						$fn.msg.success('添加成功！')
						if (violation?.length) this.tipsModalRef.refs.ref.open(violation)
						this.fetch()
					})
				}
			}, {tabIndex: -1}),
			TableControls.click.call(this, '信息', () => this.infoModalRef.refs.ref.open(rows, levels), {tabIndex: -1, disabled: !rows.uuid}),
			TableControls.click.call(this, '动作', () => this.actionModalRef.refs.ref.open(rows.uuid), {tabIndex: -1, disabled: !rows.uuid}),
			TableControls.click.call(this, '备注', () => this.remarkModalRef.refs.ref.open(rows.uuid), {tabIndex: -1, disabled: !rows.uuid}),
			TableControls.click.call(this, '删除', () => {
				confirm.then( f => {
					f({
						msg: '确认删除?',
						onOk: async close => {
							$http.submit(null, 'qc-data/del',{ param:{uuid: rows.uuid}, loadingText:`删除中`}).then(()=>{
								close()
								this.fetch()
								$fn.msg.success('删除成功')
							})
						}
					})
				})
			}, {tabIndex: -1, disabled: !rows.uuid })
		]
	}
	
	render(){
		return <>
			<div className='ex fv tableIndex'>
				{ SearchForm.call(this) }
				{ Table.call(this, {isIndex: true}) }
			</div>
			<RemarkModal ref={ref => this.remarkModalRef = ref} />
			<ActionModal ref={ref => this.actionModalRef = ref} />
			<InfoModal ref={ref => this.infoModalRef = ref} />
			<TipsModal ref={ref => this.tipsModalRef = ref} />
		</>
	}
}

export default Index